package cn.yanxiaohui.service.web.service;

import java.util.Date;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import cn.yanxiaohui.common.exception.APIException;
import cn.yanxiaohui.common.exception.APIExceptionErrorCode.BizError;
import cn.yanxiaohui.common.service.BaseService;
import cn.yanxiaohui.common.util.DecoderOrEncoderUtils;
import cn.yanxiaohui.common.util.constant.UserEnum;
import cn.yanxiaohui.data.entity.User;
import cn.yanxiaohui.data.mapper.UserMapper;

/**
 * 用户业务层
 * @author yanxh
 *
 */
@Service
public class UserService extends BaseService<UserMapper,User>{
	
	@Autowired
	UserMapper userMapper;
	
	public User UserById(Long id) {
		return userMapper.selectByPrimaryKey(id);
	}
	
	public User userByUserName(String userName) {
		return userMapper.userByUserName(userName);
	}

	public void insertUser(User user) throws APIException{
		String userName = user.getUserName();
		User result = userMapper.userByUserName(userName);
		if(result != null){
			throw new APIException(BizError.USER_SAME.getCode(),
					BizError.USER_SAME.getMessage());
		}
		String password = user.getPassword();
		if(StringUtils.isBlank(password)){
			throw new APIException(BizError.PASSWORD_IS_NULL.getCode(),
					BizError.PASSWORD_IS_NULL.getMessage());
		}
		password = DecoderOrEncoderUtils.getEncoderStr(password);
		user.setPassword(password);
		Date date = new Date();
		user.setType(UserEnum.Type.NORMAL.getType());
		user.setCreateTime(date);
		user.setUpdateTime(date);
		userMapper.insertSelective(user);
	}

	public List<User> listByParams(Map<String,Object> params){
		return userMapper.listByParams(params);
	}
}
